﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NVelocity.App;
using NVelocity;
using NBusiness.CodeDom;
using System.IO;
using NBusiness.CodeDom.Compiler;

namespace NBusiness.Templates.Engines.NVelocity
{
    public class NVelocityEngine : ICodeGeneratorEngine
    {
        #region ICodeGeneratorEngine Members

        public string Generate(Entity entity, string template, EntityCompileParameters parameters)
        {
            StringBuilder sb = new StringBuilder();
            string oldPath = Directory.GetCurrentDirectory();
            string temp = Path.GetTempFileName();
            try
            {
                Directory.SetCurrentDirectory(Path.GetDirectoryName(temp));

                Velocity.Init();
                VelocityContext context = new VelocityContext();
                context.Put("entity", entity);

                File.WriteAllText(temp, template);
                Template templateFile = Velocity.GetTemplate(Path.GetFileName(temp));

                using (TextWriter writer = new StringWriter(sb))
                {
                    templateFile.Merge(context, writer);
                }
            }
            finally
            {
                Directory.SetCurrentDirectory(oldPath);
            }
            
            return sb.ToString();
        }

        #endregion
    }
}
